<!--
 @description 购物车单项
 @fileName index.vue
 @author zengqiongying
 @created 2022/07/30 15:01:44
-->
<template>
  <div>
    <van-swipe-cell
      ref="swipeCell"
      :name="cartData.id"
      :before-close="beforeClose"
      :disabled="disEdit"
      @close="onCloseCell"
      @open="onOpenCell"
    >
      <div class="cart-cell">
        <div class="cart-item">
          <div class="item-cell" @click="handleClickCheck">
            <div class="item-check" :class="{'checked':cartData.checked}" />
          </div>
          <div class="item-image" @click="handleClickPro">
            <ImageVideo :src="cartData.mainPicUrl" fit="fill" />
          </div>
          <div class="item-cell item-content">
            <div class="name">{{ cartData.skuName }}</div>
            <div class="cell">
              <span v-if="cartData.isActivity===1" class="icon-special-price" />
              <span v-else>原价：</span>
              <span>{{ cartData.orangePrice || 0 }} 元</span>
            </div>

            <div v-if="cartData.productFlag && ['03','05'].includes(cartData.productFlag)" class="cell">单价： 0 元</div>

            <div v-else class="cell">
              <span>单价：</span>
              <van-field
                v-model="salePrice"
                :disabled="disPrice || disEdit"
                class="price"
                type="number"
                label=""
                format-trigger="onBlur"
                :formatter="formatterPrice"
              />
              <span> 元</span>
            </div>

            <div class="tags">
              <template v-if="cartData.productFlag==='05'">
                <span class="tag">样</span>
                <span class="tag">赠</span>
              </template>
              <span v-if="cartData.productFlag==='02'" class="tag">样</span>
              <span v-if="cartData.productFlag==='03'" class="tag">赠</span>
            </div>
            <div class="number">
              <van-stepper v-model="quantity" :disabled="disQuantity || disEdit" integer step="1" min="1" max="1000" @change="handleQuantityChange" />
            </div>
          </div>
        </div>
      </div>
      <template #right>
        <div class="swip-btns">
          <van-button square text="备注" type="danger" class="btn comment" @click="handleClickComment" />
          <van-button square text="删除" type="danger" class="btn del" @click="handleClickDel" />
        </div>
      </template>
    </van-swipe-cell>
    <Remark
      v-if="showRemark"
      :show.sync="showRemark"
      :cart-id="cartData.id"
      :remark="cartData.remark"
      :success-fnc="remarkSuccessFnc"
      @success="handleRemarkSuccess"
    />
  </div>
</template>

<script>
import ImageVideo from '@/components/ImageVideo'
import Remark from '../Remark'
import { modifySalePrice, modifyQuantity, deleteShoppingCart } from '@/apis/cart'
export default {
  name: 'CartItem',
  components: {
    ImageVideo,
    Remark
  },
  props: {
    disEdit: {
      type: Boolean,
      default: false
    },
    cartData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      quantity: 1,
      salePrice: 0,
      disPrice: false,
      disQuantity: false,
      activeBtnType: '', // 操作按钮类型：delete 删除 ， remark 备注
      showRemark: false,
      remarkSuccessFnc: null,
      swipeOpen: false
    }
  },
  computed: {
    isActivity() {
      return Number(this.cartData.isActivity || 0) === 1
    }
  },
  watch: {
    'cartData.salePrice'(val, oldVal) {
      this.salePrice = val || 1
    },
    'cartData.quantity'(val, oldVal) {
      this.quantity = val || 1
    }
  },
  created() {
    this.salePrice = this.cartData.salePrice
    this.quantity = this.cartData.quantity
  },
  methods: {
    // 格式化销售价格
    formatterPrice(value) {
      const val = Math.floor(value * 100) / 100
      const oldPrice = Number(this.cartData.salePrice || 0)
      if (val === oldPrice) {
        return val
      }
      const orangePrice = Number(this.cartData.orangePrice || 0)
      if (val < 0) {
        this.$toast('输入价格不能小于0')
        return oldPrice
      }
      if (orangePrice > 0 && val > orangePrice) {
        this.$toast(`输入价格不能大于${this.isActivity ? '特价' : '原价'}`)
        return oldPrice
      }
      const params = {
        salePrice: val,
        shoppingCartId: this.cartData.id
      }
      this.$emit('update:disEdit', true)
      this.disPrice = true
      modifySalePrice(params).then(res => {
        if (res.success === 1) {
          this.$set(this.cartData, 'salePrice', val)
          this.$nextTick(() => {
            this.$emit('change')
          })
        } else {
          this.salePrice = this.cartData.salePrice
        }
        this.disPrice = false
        this.$emit('update:disEdit', false)
      }).catch(() => {
        this.salePrice = this.cartData.salePrice
        this.disPrice = false
        this.$emit('update:disEdit', false)
      })
      return val
    },
    // 变更数量
    handleQuantityChange(value) {
      const oldQuantity = Number(this.cartData.quantity)
      if (oldQuantity === value) return
      const params = {
        quantity: Number(value),
        shoppingCartId: this.cartData.id
      }
      this.$emit('update:disEdit', true)
      this.disQuantity = true
      modifyQuantity(params).then(res => {
        if (res.success === 1) {
          this.$set(this.cartData, 'quantity', value)
          this.$nextTick(() => {
            this.$emit('change')
          })
        } else {
          this.quantity = oldQuantity
        }
        this.disQuantity = false
        this.$emit('update:disEdit', false)
      }).catch(() => {
        this.quantity = oldQuantity
        this.disQuantity = false
        this.$emit('update:disEdit', false)
      })
    },
    handleClickPro() {
      const { spuId, skuId } = this.cartData
      this.$router.push({
        name: 'FinishedDetail',
        params: { spuId, skuId }
      })
    },
    handleClickCheck() {
      this.$set(this.cartData, 'checked', !this.cartData.checked)
      this.$emit('checked')
    },
    handleClickDel() {
      this.activeBtnType = 'delete'
    },
    handleClickComment() {
      this.activeBtnType = 'remark'
    },
    handleRemarkSuccess(content) {
      this.$set(this.cartData, 'remark', content)
      this.$emit('comment')
    },
    closeSwipe() {
      this.$refs.swipeCell.close()
    },
    onOpenCell() {
      this.swipeOpen = true
      this.$emit('open')
    },
    onCloseCell() {
      this.swipeOpen = false
    },
    /**
     * position 为关闭时点击的位置
     * instance 为对应的 SwipeCell 实例
    */
    beforeClose({ position, instance }) {
      const shoppingCartId = this.cartData.id
      switch (position) {
        case 'cell':
          this.activeBtnType = ''
          instance.close()
          break
        /* case 'outside':
          this.activeBtnType = ''
          instance.close()
          break */
        case 'right':
          if (this.activeBtnType === 'delete') {
            this.$dialog.confirm({
              title: '确认删除',
              message: '您确定要删除当前所选商品吗？'
            }).then(() => {
              const ids = [shoppingCartId]
              deleteShoppingCart(ids).then(res => {
                if (res.success === 1) {
                  this.$toast('删除成功')
                  instance.close()
                  this.$emit('del', shoppingCartId)
                }
              })
            })
          } else if (this.activeBtnType === 'remark') {
            this.remarkSuccessFnc = () => {
              instance.close()
            }
            this.$nextTick(() => {
              this.showRemark = true
            })
          }
          break
      }
    }
  }
}

</script>
<style lang='less' scoped>
.cart-cell{
  padding: 0 16px;
  margin-bottom: 10px;
}
.cart-item{
  padding:  20px 0;
  box-shadow: 0px 0px 30px 0px rgba(60,88,88,0.05);
  border-radius: 12px;
  background: #fff;
  display: flex;
  .item-cell{
    padding:0 10px;
  }
  .item-check{
    margin-top: 56px;
    width: 20px;
    height: 20px;
    border: 2px solid #D2D2D2;
    border-radius: 50%;
    box-sizing: border-box;
    background: #fff;
    &.checked{
      background:url(~@/assets/my/checked.png) no-repeat;
      background-size: 20px 20px;
      border: 0;
    }
  }
  .item-image{
    width: 110px;
    height: 110px;
    background: #D8D8D8;
    border-radius: 12px;
    overflow: hidden;
  }
  .item-content{
    flex: 1;
    .cell{
      margin-top: 8px;
      min-height: 20px;
      line-height: 20px;
      color: #999999;
      font-size: 14px;
      display: flex;
      align-items: center;
    }
    .name{
      max-height: 40px;
      line-height: 20px;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      -webkit-line-clamp:2;
      font-size: 14px;
    }
    .icon-special-price{
      margin-right: 4px;
      width: 41px;
      height:16px;
      background: url(~@/assets/my/icon-special-price.png) no-repeat;
      background-size: 41px 16px;
    }
    .tags{
      height: 20px;
      margin-top: 8px;
      .tag{
        display: inline-block;
        padding: 4px;
        line-height: 1;
        background: rgba(234, 91, 49, .1);
        border-radius: 6px;
        margin-right: 8px;
        color: #FF6345;
        font-size: 10px;
        text-align: center;
      }
    }
    .price{
      margin-right: 4px;
      width: 80px;
      height: 26px;
      line-height: 20px;
      background: #F9F9F9;
      border-radius: 2px;
      padding: 3px;
      /deep/.van-field__control{
        text-align: center;
        color: #EA5B31;
      }
    }
    .number{
      margin-top: -2px;
      display: flex;
      justify-content: flex-end;
      /deep/ .van-stepper{
        height: 28px;
        border-radius: 6px;
        border: 1px solid #979797;
        overflow: hidden;
        box-sizing: border-box;
        .van-stepper__input{
          width: 48px;
          height: 26px;
          background: #fff;
        }
        .van-stepper__plus,.van-stepper__minus{
          width: 26px;
          height: 26px;
          background: #fff;
        }
        .van-stepper__plus {
          border-left: 1px solid #979797;
        }
        .van-stepper__minus{
          border-right: 1px solid #979797;
        }
      }
    }
  }
}
.swip-btns{
  display: flex;
  position: relative;
  height: 100%;
  box-sizing:border-box;
  .btn{
    position: relative;
    width: 66px;
    height: 100%;
    padding: 0;
    border: 0;
    font-size: 14px;
    &.comment{
      background: #FFB450;
      border-radius: 10px 0px 0px 10px;
    }
    &.del{
      background: #F94B4B;
      border-radius: 0px 10px 10px 0px;
      margin-right: 16px;
    }
  }
}
</style>
